package me.ezitku.base.Socket

import com.ug_project.Async.runASync
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress

/**
 * Created by yurqi on 2017/5/31.
 */

private var udpSocket = DatagramSocket(SocketConst.DEFAULT_UDP_PORT)
private var isClosed = false
private var CLOSE = "close"
/**
 *
 */
fun createUdpSocket(bufferSize: ByteArray, action: (DatagramPacket) -> Unit): DatagramSocket {
    //val udpSocket = DatagramSocket(DEFAULT_SOCKET_PORT)
    isClosed = false
    runASync {
        while (!isClosed) {
            var receiverPacket = DatagramPacket(bufferSize, bufferSize.size)
            udpSocket.receive(receiverPacket)
            var msg = String(receiverPacket.data)
            if (msg.startsWith(CLOSE)) {
                //udpSocket.close()
                udpSocket.disconnect()
                isClosed = true
            } else {
                isClosed = false
                action.invoke(receiverPacket)
            }
        }
    }
    return udpSocket
}

fun sendUdpSocket(sendData: String, ipAddress: String = "255.255.255.255") {
    sendUdpSocket(sendData.toByteArray(), ipAddress)
}

fun closeUdpScoket(ipAddress: String = "255.255.255.255") {
    sendUdpSocket(CLOSE, ipAddress)
}

fun sendUdpSocket(sendData: ByteArray, ipAddress: String = "255.255.255.255") {
    runASync {
        repeat(2) {
            delay(200)
            pingIpAddress(ipAddress)
        }
        var inetAddress = InetAddress.getByName(ipAddress)
        var sendPacket = DatagramPacket(sendData, sendData.size, inetAddress, SocketConst.DEFAULT_UDP_PORT)
        udpSocket.send(sendPacket)

    }
}


private fun pingIpAddress(ipAddress: String): Boolean {
    try {
        val process = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 100 " + ipAddress)
        val status = process.waitFor()
        return status == 0
    } catch (e: IOException) {
        e.printStackTrace()
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }

    return false
}